﻿Imports Mystery
Imports System.Reflection

Public Class BackReferenceAttribute
    Inherits MysteryPropertyAttribute

    Public Property incoming_ref As PropertyInfo

    Public Overrides Sub setup()
        If incoming_ref Is Nothing Then
            Dim refered_type As Type = Me.used_in.PropertyType.GetGenericArguments().FirstOrDefault
            'should be a content
            refered_type.GetInterfaceMap(GetType(IContent))
            'make sure it is registered
            getMystery.AssemblyRegister.registerType(refered_type)
            Dim content_type As ContentType = refered_type.getMysteryAttribute(Of ContentType)()
            If content_type Is Nothing Then Throw New Exception("the reference type should be a content type")
            Dim references As IEnumerable(Of ContentReference) = getMystery.AssemblyRegister.getMysteryPropertyAttributes(Of ContentReference)(refered_type)
            references = New HashSet(Of ContentReference)(From x As ContentReference In references Select x Where x.used_in.PropertyType.GetGenericArguments.FirstOrDefault Is Me.used_in.DeclaringType)
            If references.Count <> 1 Then
                Throw New Exception(content_type.name & " have not a unique reference to " & Me.used_in.DeclaringType.FullName)
            Else
                incoming_ref = references.FirstOrDefault.used_in
            End If

        End If
    End Sub

End Class
